# pip3 install pillow  -i https://pypi.tuna.tsinghua.edu.cn/simple
# tinify
import logging.handlers
import os
import time
from PIL import Image
import tinify

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
fh = logging.handlers.RotatingFileHandler("img_compress.log", mode='a', maxBytes=10 * 1024 * 1024, backupCount=5)
LOG_FORMAT = "[%(asctime)s]:%(levelname)s-[%(funcName)s]:%(message)s"
fh.setFormatter(logging.Formatter(LOG_FORMAT))
logger.addHandler(fh)
ch = logging.StreamHandler()
ch.setFormatter(logging.Formatter(LOG_FORMAT))
logger.addHandler(ch)

tinify.key = 'sT4tKbn1pzy2dLtj0My3fKCC5vQxBky0'
# tinify.proxy = "<TINIFT_PROXY>"
PROJECT_NAME = 'official'
FRONTEND_DIST_DIR = '<FRONTEND_DIST_DIR>'
QUALITY = 20
time_str = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
FRONTEND_DIST_DIR = PROJECT_NAME + '_' + '_compress_' + time_str


def compress_images(path, detail_type):
    # 创建压缩图片存放目录
    new_dir = os.path.join(os.path.dirname(path), FRONTEND_DIST_DIR)
    logger.debug('压缩至目录：%s', new_dir)
    os.mkdir(new_dir)

    # 遍历文件夹压缩图片
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith('.jpg') or file.endswith('.png'):
                # 打开原始图片
                img_path = os.path.join(root, file)
                logger.debug('打开原始图片：%s', img_path)

                # 创建压缩后图片路径
                new_path = os.path.join(new_dir, os.path.relpath(img_path, path))
                os.makedirs(os.path.dirname(new_path), exist_ok=True)

                # 分类型进行压缩处理
                if detail_type == 'pil':
                    compress_by_pil(img_path, new_path)
                elif detail_type == 'tiny':
                    compress_by_tiny(img_path, new_path)
                else:
                    logger.debug('detail_type应为pil或tiny')
    logger.debug('压缩完成!')


def compress_by_pil(img_path, new_path):
    img = Image.open(img_path)
    img.save(new_path, optimize=True, quality=QUALITY)
    logger.debug('保存压缩图片：%s', new_path)


def compress_by_tiny(img_path, new_path):
    img = tinify.from_file(img_path)
    img.to_file(new_path)
    logger.debug('保存压缩图片：%s', new_path)


def main():
    logger.info(__file__)
    logger.info(os.environ)
    compress_images('./test/webdata', 'tiny')


if __name__ == "__main__":
    main()
